package com.iwith.dongmoon.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.iwith.dongmoon.util.SessionManager;

public class LoginActivity extends Activity implements OnClickListener{
	public final static int LOGIN_ACTIVITY = 11000;

	private SessionManager mSessionManager=null;
	
	private EditText loginId;
	private EditText loginPassword;
	private Button loginButton;
	private CheckBox autoLogin;
	private Button signupButton;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login);
		// TODO Auto-generated method stub
		
		mSessionManager=new SessionManager(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		Initialize();
	}

	private void Initialize() {
		loginId = (EditText) findViewById(R.id.login_id);
		loginPassword = (EditText) findViewById(R.id.login_password);
		loginButton = (Button) findViewById(R.id.login_loginbt);
		autoLogin = (CheckBox) findViewById(R.id.login_autologin);
		signupButton = (Button) findViewById(R.id.login_signupbt);

		loginButton.setOnClickListener(this);
		signupButton.setOnClickListener(this);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);

		if (resultCode == RESULT_OK) {
			loginId.setText(intent.getExtras().getString("userid"));
			loginPassword.setText(intent.getExtras().getString("password"));
		}
	}

	private void login() {
		String userid = loginId.getText().toString().trim();
		String password = loginPassword.getText().toString().trim();

		if (userid.length() < 1) {
			Toast.makeText(this, "아이디를 입력해주세요", Toast.LENGTH_SHORT).show();
		}

		else if (password.length() < 1) {
			Toast.makeText(this, "비밀번호를 입력해주세요", Toast.LENGTH_SHORT).show();
		}

		else {
			if (mSessionManager.login(false, userid, password) == true) {
				mSessionManager.saveUserInfo(autoLogin.isChecked(), userid,	password);
				finish();
			}
		}
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId()==loginButton.getId()){
			login();
		} else if(v.getId()==signupButton.getId()){
			Intent intent = new Intent(this, SignUpDocumentActivity.class);
			startActivityForResult(intent, LOGIN_ACTIVITY);
		}
	}
}
